package com.gupaoedu.baifc.dynamicproxy.myproxy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * projectName: baifc_proxy
 * packageName: com.gupaoedu.baifc.dynamicproxy.myproxy
 * Created: 2019/3/18.
 * Auther: baifc
 * Description:
 */
public class MyClassLoader extends ClassLoader {

    private File classPathFile;

    public MyClassLoader(){
        String classPath = MyClassLoader.class.getResource("").getPath();

        System.out.println("classPath = " + classPath);

        this.classPathFile = new File(classPath);
    }

    protected Class<?> findClass(String name) {

        String className = MyClassLoader.class.getPackage().getName() + "." + name;

        System.out.println("className = " + className);

        if(classPathFile != null){
            File classFile = new File(classPathFile,name.replaceAll("\\.","/") + ".class");

            if(classFile.exists()){
                System.out.println("classFile.getPath() = " + classFile.getPath());
                FileInputStream in = null;
                ByteArrayOutputStream out = null;
                try{
                    in = new FileInputStream(classFile);
                    out = new ByteArrayOutputStream();
                    byte [] buff = new byte[1024];

                    int len;
                    while ((len = in.read(buff)) != -1){
                        out.write(buff,0,len);
                    }

                    return defineClass(className, out.toByteArray(), 0, out.size());

                } catch (Exception e){
                   e.printStackTrace();
                } finally {
                    if(in != null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    if(out != null){
                        try {
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

}
